#!/bin/bash

BUS=7
ADDR=0x30
REG=0
LEN=8

if [ $# -ge 1 ]
then
	BUS=$1
fi

if [ $# -ge 2 ]
then
	ADDR=$2
fi

if [ $# -ge 3 ]
then
	REG=$2
fi

if [ $# -ge 4 ]
then
	LEN=$2
fi

set_cpld_version()
{
    OBJ='xyz.openbmc_project.Software.BMC.Updater'
    OBJ_PATH="/xyz/openbmc_project/software/cpld_active"
    OBJ_PATH="/xyz/openbmc_project/software/cpld_active"
    INTERFACE='xyz.openbmc_project.Software.Version'
    PROPERTY='Version'
    
    busctl set-property  $OBJ $OBJ_PATH $INTERFACE $PROPERTY s "$1"
    return 0
}
times=10
if [ $# -ge 1 ]
then
	times=$1
fi
#update cpld.
echo "get cpld version starting"

while true
do 
	str="`i2ctransfer -y $BUS w1@$ADDR $REG r$LEN`"
	if [ $? -ne 0 ]
	then
		sleep 3
		set_cpld_version "null"
		if [ $times -gt 0 ]
		then
			let times--
			continue
		else
			exit 1
		fi
	fi
	str=`echo $str | sed 's/0x//g' | sed 's/ //g'`
	set_cpld_version $str
	exit 0
done
echo "set cpld version finish"
